<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Model\CancelBlackLog;
use App\Model\UserBlackList;
use App\Model\UserProfile;
use App\Util\InfoUtil;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;

class CancelBlackController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {
            $content->header("取消黑名单列表");
            $content->description('');
            $content->body($this->grid());
        });
    }

    public function create()
    {
        return Admin::content(function (Content $content) {
            $content->header('添加');
            $content->description('');
            $content->body($this->form());
        });
    }

    protected function grid()
    {
        return Admin::grid(CancelBlackLog::class, function (Grid $grid) {
            $grid->model()->orderBy('id', 'desc');
            $grid->user_id('用户ID');
            $grid->black_user_id('黑名单用户');
            $grid->updated_by('操作人员');

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableView();
                $actions->disableEdit();
            });
        });
    }

    protected function form($mode = '', $id = '')
    {
        return Admin::form(CancelBlackLog::class, function (Form $form) use ($mode, $id) {
            $form->text('user_id', '用户ID')->required();
            $form->text('black_user_id', '黑名单用户')->required();

            $form->saving(function (Form $form) {
                $users = UserProfile::getInfoByProfileId($form->user_id);
                $blackUsers = UserProfile::getInfoByProfileId($form->black_user_id);

                if (!UserBlackList::check($users->user_id, $blackUsers->user_id)) {
                    return InfoUtil::adminErr('用户不存在拉黑！');
                }

                CancelBlackLog::delBlack($users->user_id, $blackUsers->user_id);

                $m = $form->model();
                $m->updated_by = auth()->user()->username;
                $m->save();
            });
        });
    }
}
